package com.ltmall.api.dao.impl;

import com.ltmall.api.bean.*;
import com.ltmall.api.dao.IWalletDAO;
import com.ltmall.api.util.PageUtil;
import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.springframework.orm.hibernate3.HibernateCallback;

import java.sql.SQLException;
import java.util.List;

public class WalletDAO extends BaseEntityDAO<WalletCash> implements IWalletDAO {

	public boolean addWalletCoupon(WalletCoupon coupon) {
		// TODO Auto-generated method stub
		try {
			getHibernateTemplate().persist(coupon);
		} catch (Exception e) {
			e.printStackTrace();
			return false;
		}
		return true;
	}

	public boolean addWalletGiftCard(WalletGiftCard giftCard) {
		// TODO Auto-generated method stub
		try {
			getHibernateTemplate().persist(giftCard);
		} catch (Exception e) {
			e.printStackTrace();
			return false;
		}
		return true;
	}

	@SuppressWarnings("rawtypes")
	public WalletCash getWalletCash(int userID) {
		List list = this.getHibernateTemplate().find(
				"from WalletCash cash where cash.userID =?",
				new Object[] { userID });
		if (list.size() > 0) {
			return (WalletCash) list.get(0);
		}
		return null;
	}

	@SuppressWarnings("rawtypes")
	public int getCouponNumber(int userID) {
		List list = this.getHibernateTemplate().find(
				"from WalletCoupon coupon where coupon.userID =?",
				new Object[] { userID });
		return list.size();
	}

	@SuppressWarnings("rawtypes")
	public int getGiftCardNumber(int userID) {
		// TODO Auto-generated method stub
		List list = this.getHibernateTemplate().find(
				"from WalletGiftCard card where card.userID =?",
				new Object[] { userID });
		return list.size();
	}

	@SuppressWarnings("unchecked")
	public List<WalletCoupon> couponList(final int userID,final PageUtil page) {
		// TODO Auto-generated method stub
		final String HQL = "from WalletCoupon coupon where coupon.userID = ? order by coupon.startTime desc";
		@SuppressWarnings("rawtypes")
		List<WalletCoupon> list = this.getHibernateTemplate().execute(
				new HibernateCallback<List>() {
					public List doInHibernate(Session session)
							throws HibernateException, SQLException {
						Query query = session.createQuery(HQL);
						query.setParameter(0, userID);
						//分页
						query.setFirstResult((page.getCur_page() - 1) * page.getNumPerPage()).setMaxResults(page.getNumPerPage());
						return query.list();
					}
				});
		return list;
	}

	@SuppressWarnings("unchecked")
	public List<WalletGiftCard> cardList(final int userID, final PageUtil page,int orderID,int type) {
		// TODO Auto-generated method stub
		String  tempHQL = null;
		int tempID = 0;
		switch(type){
		case 1://userID
			tempHQL = "from WalletGiftCard card where card.userID = ? and card.orderID = 0 and card.activation =1 order by card.startTime desc";
			tempID = userID;
			break;
		case 2://orderID
			tempHQL = "from WalletGiftCard card where card.orderID = ? order by card.startTime desc";
			tempID = orderID;
			break;
		}
		final String HQL = tempHQL;
		final int ID = tempID;
		@SuppressWarnings("rawtypes")
		List<WalletGiftCard> list = this.getHibernateTemplate().execute(
				new HibernateCallback<List>() {
					public List doInHibernate(Session session)
							throws HibernateException, SQLException {
						Query query = session.createQuery(HQL);
						query.setParameter(0, ID);
						// 分页
						query.setFirstResult(
								(page.getCur_page() - 1) * page.getNumPerPage())
								.setMaxResults(page.getNumPerPage());
						return query.list();
					}
				});
		return list;
	}

	public boolean cardActivation(int userID, int cardID, String code) {
		// TODO Auto-generated method stub
		String hql = "update WalletGiftCard card set card.activation = ?,card.userID = ?"
				+ "where card.cardID =? and card.activationCode = ?";
		try {
			Query query = getSession().createQuery(hql);
			query.setParameter(0, 1);
			query.setParameter(1, userID);
			query.setParameter(2, cardID);
			query.setParameter(3, code);
			int temp = query.executeUpdate();
			if (temp == 1) {
				return true;
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return false;
	}

	@SuppressWarnings("rawtypes")
	public WalletCoupon getCoupon(int couponID, int userID) {
		List list = this.getHibernateTemplate().find(
				"from WalletCoupon coupon where coupon.couponID =? and coupon.userID = ?",
				new Object[] { couponID,userID });
		if (list.size() > 0) {
			return (WalletCoupon) list.get(0);
		}
		return null;
	}

	public boolean updateCouponInvalid(int couponID, int userID) {
		// TODO Auto-generated method stub
		String hql = "update WalletCoupon coupon set coupon.valid = ?"
				+ "where coupon.couponID = ? and coupon.userID =? ";
		try {
			Query query = getSession().createQuery(hql);
			query.setParameter(0, 0);
			query.setParameter(1, couponID);
			query.setParameter(2, userID);
			int temp = query.executeUpdate();
			if (temp == 1) {
				return true;
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return false;
	}

	public boolean addGiftCardCount(WalletGiftCardCount count) {
		count.setOpTime(System.currentTimeMillis());
		// TODO Auto-generated method stub
		try {
			getHibernateTemplate().persist(count);
		} catch (Exception e) {
			e.printStackTrace();
			return false;
		}
		return true;
	}

	public boolean updateGiftCardOwner(int cardID, int userID) {
		// TODO Auto-generated method stub
		String hql = "update WalletGiftCard wgc set wgc.userID = ? where wgc.cardID = ?";
		try {
			Query query = getSession().createQuery(hql);
			query.setParameter(0, userID);
			query.setParameter(1, cardID);
			int temp = query.executeUpdate();
			if (temp == 1) {
				return true;
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return false;
	}

	@SuppressWarnings("rawtypes")
	public WalletGiftCard getGiftCard(int cardID) {
		List list = this.getHibernateTemplate().find(
				"from WalletGiftCard wgc where wgc.cardID =?",
				new Object[] { cardID });
		if (list.size() > 0) {
			return (WalletGiftCard) list.get(0);
		}
		return null;
	}

	public boolean updateGiftCardOwnerASBuyer(int cardID) {
		// TODO Auto-generated method stub
		String hql = "update WalletGiftCard wgc set wgc.userID = wgc.buyer where wgc.cardID = ?";
		try {
			Query query = getSession().createQuery(hql);
			query.setParameter(0, cardID);
			int temp = query.executeUpdate();
			if (temp == 1) {
				return true;
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return false;
	}

	@SuppressWarnings("rawtypes")
	public WalletGiftCardCount getgiftCardCount(int userID) {
		// TODO Auto-generated method stub
		List list = this.getHibernateTemplate().find(
				"from WalletGiftCardCount wgc where wgc.userID =?",
				new Object[] { userID });
		if (list.size() > 0) {
			return (WalletGiftCardCount) list.get(0);
		}
		return null;
	}

	public boolean updategiftCardCount(int userID, float money) {
		// TODO Auto-generated method stub
		String hql = "update WalletGiftCardCount wcc set wcc.money = wcc.money + ?"
				+ "where wcc.userID = ?";
		try {
			Query query = getSession().createQuery(hql);
			query.setParameter(0, money);
			query.setParameter(1, userID);
			int temp = query.executeUpdate();
			if (temp == 1) {
				return true;
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return false;
	}

	public boolean setGiftcardCode(int cardID, String code) {
		// TODO Auto-generated method stub
		String hql = "update WalletGiftCard wc set wc.code = ?"
				+ "where wc.cardID = ?";
		try {
			Query query = getSession().createQuery(hql);
			query.setParameter(0, code);
			query.setParameter(1, cardID);
			int temp = query.executeUpdate();
			if (temp == 1) {
				return true;
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return false;
	}

	public boolean addGiftcradOrder(GiftCardOrder order) {
		order.setOpTime(System.currentTimeMillis());
		try {
			getHibernateTemplate().persist(order);
		} catch (Exception e) {
			e.printStackTrace();
			return false;
		}
		return true;
	}

	@SuppressWarnings("unchecked")
	public List<GiftCardOrder> orderList(final int userID,final PageUtil page) {
		// TODO Auto-generated method stub
		final String HQL = "from GiftCardOrder orde where orde.userID = ? and orde.station!=0 order by orde.opTime desc";
		@SuppressWarnings("rawtypes")
		List<GiftCardOrder> list = this.getHibernateTemplate().execute(
				new HibernateCallback<List>() {
					public List doInHibernate(Session session)
							throws HibernateException, SQLException {
						Query query = session.createQuery(HQL);
						query.setParameter(0, userID);
						// 分页
						query.setFirstResult(
								(page.getCur_page() - 1) * page.getNumPerPage())
								.setMaxResults(page.getNumPerPage());
						return query.list();
					}
				});
		return list;
	}

	@SuppressWarnings("rawtypes")
	public GiftCardOrder getGiftCardOrder(int orderID, int userID) {
		List list = this.getHibernateTemplate().find(
				"from GiftCardOrder orde where orde.orderID =? and orde.userID =?",
				new Object[] { orderID,userID});
		if (list.size() > 0) {
			return (GiftCardOrder) list.get(0);
		}
		return null;
	}

	public boolean updateCardCode(int orderID, String code) {
		// TODO Auto-generated method stub
		String hql = "update GiftCardOrder orde set orde.code = ?,orde.opTime = ?"
				+ "where orde.orderID = ? ";
		try {
			Query query = getSession().createQuery(hql);
			query.setParameter(0,code);
			query.setParameter(1, System.currentTimeMillis());
			query.setParameter(2, orderID);
			int temp = query.executeUpdate();
			if (temp == 1) {
				return true;
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return false;
	}

	public boolean updateCardCodeStation(int orderID, int station) {
		// TODO Auto-generated method stub
		String hql = "update GiftCardOrder orde set orde.station = ?"
				+ "where orde.orderID = ? ";
		try {
			Query query = getSession().createQuery(hql);
			query.setParameter(0, station);
			query.setParameter(1, orderID);
			int temp = query.executeUpdate();
			if (temp == 1) {
				return true;
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return false;
	}

	public List<ThRechargeRecord> getRechargeRecordsByUser(final int userID, final PageUtil page) {
		// TODO Auto-generated method stub
		final String HQL = "from ThRechargeRecord where userId = ? AND state = 2 order by createdAt DESC";
        @SuppressWarnings("unchecked")
        List<ThRechargeRecord> list = this.getHibernateTemplate().execute(new HibernateCallback<List>() {
        	public List doInHibernate(Session session) throws HibernateException, SQLException {
        		Query query = session.createQuery(HQL);
        		query.setParameter(0, userID);
                query.setFirstResult((page.getCur_page() - 1) * page.getNumPerPage())
						.setMaxResults(page.getNumPerPage());
                return query.list();
            }
        });
        return list;
	}

	public List<ThOutcomeRecord> getOutcomeRecordsByUser(final int userID, final PageUtil page) {
		// TODO Auto-generated method stub
		final String HQL = "from ThOutcomeRecord where userId = ? order by createdAt DESC";
        @SuppressWarnings("unchecked")
        List<ThOutcomeRecord> list = this.getHibernateTemplate().execute(new HibernateCallback<List>() {
        	public List doInHibernate(Session session) throws HibernateException, SQLException {
        		Query query = session.createQuery(HQL);
        		query.setParameter(0, userID);
                query.setFirstResult((page.getCur_page() - 1) * page.getNumPerPage())
						.setMaxResults(page.getNumPerPage());
                return query.list();
            }
        });
        return list;
	}

	public ThHcWallet getWalletByUser(int userID) {
		// TODO Auto-generated method stub
		String HQL = "from ThHcWallet where userId = ?";
		List list = this.getHibernateTemplate().find(HQL, new Object[] { userID });
		if (list.size() > 0) {
			return (ThHcWallet) list.get(0);
		}
		return null;
	}

	public ThRechargeChannel getRechargeChannelByID(int channelID) {
		// TODO Auto-generated method stub
		String HQL = "from ThRechargeChannel where id = ?";
		List list = this.getHibernateTemplate().find(HQL, new Object[] { channelID });
		if (list.size() > 0) {
			return (ThRechargeChannel) list.get(0);
		}
		return null;
	}

	public boolean rechargeRecordCreate(ThRechargeRecord record) {
		// TODO Auto-generated method stub
		try {
			getHibernateTemplate().persist(record);
		} catch (Exception e) {
			e.printStackTrace();
			return false;
		}
		return true;
	}

	public boolean rechargeRecordUpdate(String tradeNo, int state) {
		// TODO Auto-generated method stub
		String hql = "update ThRechargeRecord set state = ? where outTradeNo = ?";
		try {
			Query query = getSession().createQuery(hql);
			query.setParameter(0, state);
			query.setParameter(1, tradeNo);
			int temp = query.executeUpdate();
			if (temp == 1) {
				return true;
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return false;
	}

	public ThRechargeRecord rechargeRecordGetByTradeNo(String tradeNo) {
		// TODO Auto-generated method stub
		String HQL = "from ThRechargeRecord where outTradeNo = ?";
		List list = this.getHibernateTemplate().find(HQL, new Object[] { tradeNo });
		if (list.size() > 0) {
			return (ThRechargeRecord) list.get(0);
		}
		return null;
	}

	public boolean freezonRecordCreate(ThFrozenRecord frozenRecord) {
		// TODO Auto-generated method stub
		try {
			getHibernateTemplate().persist(frozenRecord);
		} catch (Exception e) {
			e.printStackTrace();
			return false;
		}
		return true;
	}
	
	public List<ThFrozenRecord> freezonRecordGetByWallet(int walletID, PageUtil page) {
		// TODO Auto-generated method stub
		return null;
	}
	
	public boolean hcWalletCreate(ThHcWallet hcWallet) {
		try {
			getHibernateTemplate().persist(hcWallet);
		} catch (Exception e) {
			e.printStackTrace();
			return false;
		}
		return true;
	}
	
	public boolean hcWalletUpdate(int user_id, int availe_amounts, int freezon_amounts) {
		// TODO Auto-generated method stub
		String hql = "update ThHcWallet set availeAmounts = ?, freezonAmounts = ? where userId = ?";
		try {
			Query query = getSession().createQuery(hql);
			query.setParameter(0, availe_amounts);
			query.setParameter(1, freezon_amounts);
			query.setParameter(2, user_id);
			int temp = query.executeUpdate();
			if (temp == 1) {
				return true;
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return false;
	}

	public boolean outcomeRecordsCreate(ThOutcomeRecord outcomeRecord) {
		// TODO Auto-generated method stub
		try {
		    getHibernateTemplate().persist(outcomeRecord);
		} catch (Exception e) {
		    e.printStackTrace();
		    return false;
		}
		return true;
	}

	public List<ThRechargeChannel> getRechargeChannelList() {
		// TODO Auto-generated method stub
		String HQL = "from ThRechargeChannel";
		List list = this.getHibernateTemplate().find(HQL);
		return list;
	}

	public boolean hcWalletAvaileUpdateByID(int amounts, int id) {
		// TODO Auto-generated method stub
		String hql = "update ThHcWallet set availeAmounts = ? where id = ?";
		try {
		    Query query = getSession().createQuery(hql);
		    query.setParameter(0, amounts);
		    query.setParameter(1, id);
		    int temp = query.executeUpdate();
		    if (temp == 1) {
		        return true;
		    }
		} catch (Exception e) {
		    e.printStackTrace();
		}
		return false;
	}
	
	public boolean addHcWalletAvaileByUserId(int amount, int userId) {
		String hql = "update ThHcWallet set availeAmounts = availeAmounts + ? where user_id = ?";
		try {
		    Query query = getSession().createQuery(hql);
		    query.setParameter(0, amount);
		    query.setParameter(1, userId);
		    int temp = query.executeUpdate();
		    if (temp == 1) {
		        return true;
		    }
		} catch (Exception e) {
		    e.printStackTrace();
		}
		return false;
	}

	public boolean hcWalletAvaileUpdateByUserID(int amounts, int userID) {
		// TODO Auto-generated method stub
		String hql = "update ThHcWallet set availeAmounts = ? where userId = ?";
		try {
		    Query query = getSession().createQuery(hql);
		    query.setParameter(0, amounts);
		    query.setParameter(1, userID);
		    int temp = query.executeUpdate();
		    if (temp == 1) {
		        return true;
		    }
		} catch (Exception e) {
		    e.printStackTrace();
		}
		return false;
	}
	public Boolean isHaveWalletByUser(final int userID) {
		// TODO Auto-generated method stub
		final String SQL = "SELECT COUNT(*) FROM TH_HC_WALLET WHERE USER_ID = ?";
		List<Integer> list = this.getHibernateTemplate().execute(
				new HibernateCallback<List>() {
					public List doInHibernate(Session session)
							throws HibernateException, SQLException {
						Query query = session.createSQLQuery(SQL);
						query.setParameter(0, userID);
						// 分页
						return query.list();
					}
				});
		if (list.size() > 0) {
			return true;
		}
		return false;
	}
	
	
}
